#include "common.h"

int main()
{
	int socketID = 0;
	//创建socket
	socketID = socket( PF_INET, SOCK_STREAM, 0);
	if ( 0 > socketID )
	{
		perror("socket error");
		exit(0);
	}
	printf("socket ok\r\n");
	//设置对方的地址
	struct sockaddr_in addr = {
		.sin_family = PF_INET,
		.sin_port   = htons(SPORT),
		.sin_addr   = {
			.s_addr = inet_addr(IP),
		},
	};
	
	//连接服务器
	int ret = connect(socketID, (struct sockaddr *)&addr, sizeof(addr));
	if (0 > ret)
	{
		perror("connect error");
		close(socketID);
		return -1;
	}
	
	//通信
	communicateToServer(socketID);
	//关闭socket
	close(socketID);
	return 0;
}

/*与服务器通信*/
int communicateToServer(int socketID)
{
	S_MSG msg = {DOWNLOAD, "123.png"};
	//发送命令+文件名
	send(socketID, &msg, sizeof(msg), 0);
	switch(msg.cmd)
	{
		case DOWNLOAD:
			recvDownloadFile(msg.fileName, socketID);
			break;
		default:
			break;
	}
	return 0;
}

/*接收下载文件，先接收文件大小，再接收文件正文内容*/
int recvDownloadFile(const char * fileName, int socketID)
{
	int size = 0 ;
	char buf[SIZE] = {0};
	int ret = 0;
	
	//接收文件大小
	ret = recv(socketID, &size, sizeof(size), 0);
	if ( sizeof(size) > ret )
	{
		printf("recv file size error, ret=%d\r\n", ret);
		return -1;
	}
	
	size = ntohl(size);
	
	//打开文件
	FILE * fp = fopen(fileName, "w");
	while (size  > 0 )
	{
		//循环接收文件内容
		ret = recv(socketID, buf, SIZE - 1, 0);
		if (0 > ret)
		{
			perror("recv error");
			break;
		}
		else if (0 == ret)
		{
			printf("断开连接\r\n");
			break;
		}
		//写内容到文件中
		fwrite(buf, 1, ret, fp);
		size -= ret;
	}
	//关闭文件
	fclose(fp);
	return 0;
}